const fileUrl = "https://www.dunlian.xyz:8443/dl/api/reimbursed/uploadFile";
Page({
  data: {
    context: null,
    imgUrl: ""
  },
  /**记录开始点 */
  bindtouchstart: function (e) {
    this.data.context.moveTo(e.changedTouches[0].x, e.changedTouches[0].y)
  },
  /**记录移动点，刷新绘制 */
  bindtouchmove: function (e) {
    this.data.context.lineTo(e.changedTouches[0].x, e.changedTouches[0].y);
    this.data.context.stroke();
    this.data.context.draw(true);
    this.data.context.moveTo(e.changedTouches[0].x, e.changedTouches[0].y);
  },
  /**清空画布 */
  clear: function () {
    this.data.context.draw();
    this.setData({
      imgUrl: ""
    })
  },
  /**导出图片 */
  export: function () {
    wx.showLoading({
      title: '提交中...',
    })
    const that = this;
    this.data.context.draw(false, wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      fileType: 'png',
      canvasId: 'firstCanvas',
      success: res => {
        const {
          tempFilePath
        } = res;
        console.log(tempFilePath,'tempFilePath');
        this.uploadImg(tempFilePath)
      },
      fail() {
        wx.showToast({
          title: '导出失败',
          icon: 'none',
          duration: 2000
        })
      }
    }))
  },
  uploadImg(filePath) {
    let ratio = 80
    if (filePath.size > 20971520) {
      wx.showToast({
        title: '图片最大不可超过20M',
        icon: "none",
      })
      return
    } else if (filePath.size > 10485760)
      ratio = 10
    else if (filePath.size > 5242880 && filePath.size < 10485760) {
      ratio = 20
    }

    wx.compressImage({
      src: filePath,
      quality: ratio,
      success: res=> {
        wx.uploadFile({
          filePath: res.tempFilePath,
          name: 'img',
          url: fileUrl,
          complete: function () {
            wx.hideLoading()
          },
          success: (v) => {
            if (v.statusCode == 200) {
              let data = JSON.parse(v.data)
              this.setData({
                imgUrl: data.data
              })
              console.log(data.data, 'data.data');
            } else {
              wx.showToast({
                title: '上传失败',
                icon: "none"
              })
            }

          }
        })
      }
    })



  },
  onShow: function () {
    const context = wx.createCanvasContext('firstCanvas')
    this.setData({
      context: context
    })
    context.draw()
  },
})